package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;

import com.atguigu.tingshu.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

//http://127.0.0.1:8500/api/album/fileUpload
    @PostMapping("fileUpload")
    @Operation(summary = "新增文件上传")
    public Result<String> fileUpload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
      //1 创建客户端
        MinioClient minioClient = new MinioClient.Builder().endpoint(minioConstantProperties.getEndpointUrl())
                .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                .build();


        // 2判断桶是否存在，不存在则创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build())){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        }
        //3完成上传，返回图片链接路径

        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + StringUtils.substringAfterLast(originalFilename, ".");
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioConstantProperties.getBucketName())
                .contentType(file.getContentType())
                .object(filename)
                        .stream(file.getInputStream(),file.getSize(),-1)
                .build());

        String url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()
                +"/"+filename;
        return Result.ok(url);
    }
}

